#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AST-based Dead Code Injector
使用抽象语法树(AST)精确定位死代码注入位置，生成更复杂和难以检测的死代码
"""

import ast
import os
import random
import subprocess
import json
from pathlib import Path
from typing import List, Dict, Optional, Tuple, Any
from dataclasses import dataclass

from core.builtin_config_module.builtin_config import BuiltInConfig
from core.utils_module.language_utils import detect_language_for_file
from core.utils_module.logger import ObfuscationLogger


@dataclass
class DeadCodeLocation:
    """死代码注入位置"""
    file_path: str
    language: str
    function_name: str
    function_start_line: int
    function_end_line: int
    complexity_score: int  # 函数复杂度评分，用于决定注入强度
    has_conditional: bool  # 函数是否已包含条件语句
    has_loop: bool  # 函数是否已包含循环


class ASTDeadCodeInjector:
    """基于AST的死代码注入器 - 生成更逼真的不可达代码"""

    # 增强的复杂度配置
    COMPLEXITY_CONFIG = {
        'low': {
            'branches_per_function': 1,
            'max_depth': 1,
            'use_opaque_predicates': False,
            'use_control_flow_obfuscation': False,
            'dead_variable_count': 2
        },
        'medium': {
            'branches_per_function': 2,
            'max_depth': 2,
            'use_opaque_predicates': True,
            'use_control_flow_obfuscation': False,
            'dead_variable_count': 4
        },
        'high': {
            'branches_per_function': 3,
            'max_depth': 3,
            'use_opaque_predicates': True,
            'use_control_flow_obfuscation': True,
            'dead_variable_count': 6
        },
        'extreme': {
            'branches_per_function': 5,
            'max_depth': 4,
            'use_opaque_predicates': True,
            'use_control_flow_obfuscation': True,
            'dead_variable_count': 10
        }
    }

    def __init__(self, config: BuiltInConfig, logger: ObfuscationLogger):
        """
        初始化AST死代码注入器

        Args:
            config: 统一配置对象
            logger: 日志记录器
        """
        self.config = config
        self.logger = logger
        self.injected_count = 0
        self.dead_code_locations: List[DeadCodeLocation] = []

    def inject_to_project(self, project_path: str,
                         complexity: Optional[str] = None,
                         probability: Optional[float] = None,
                         use_ast: bool = True) -> bool:
        """
        向项目注入死代码

        Args:
            project_path: 项目路径
            complexity: 复杂度 low/medium/high/extreme
            probability: 注入概率 (0.0-1.0)
            use_ast: 是否使用AST分析

        Returns:
            是否成功
        """
        try:
            # 使用参数或配置
            complexity = (
                complexity
                if complexity is not None
                else self.config.advanced_features.dead_code_complexity
            )
            probability = (
                probability
                if probability is not None
                else self.config.advanced_features.dead_code_injection_probability
            )

            if project_path and not os.path.exists(project_path):
                self.logger.log_error(f"项目路径不存在: {project_path}")
                return False

            self.logger.log_operation(
                "AST死代码注入",
                f"复杂度: {complexity}, 注入概率: {probability}, AST模式: {use_ast}"
            )

            # 查找目标文件
            target_files = self._find_target_files(project_path)

            if not target_files:
                self.logger.log_warning("没有找到目标文件")
                return False

            self.logger.log_operation("目标文件", f"找到 {len(target_files)} 个文件")

            # 使用AST分析函数结构
            if use_ast:
                self._analyze_code_structure(target_files)
                self.logger.log_operation(
                    "代码结构分析",
                    f"发现 {len(self.dead_code_locations)} 个可注入位置"
                )

            # 注入死代码
            self.injected_count = 0
            for file_path in target_files:
                # 根据概率决定是否注入
                if random.random() < probability:
                    if use_ast and self.dead_code_locations:
                        if self._inject_with_ast(file_path, complexity):
                            self.injected_count += 1
                    else:
                        if self._inject_with_regex(file_path, complexity):
                            self.injected_count += 1

            self.logger.log_operation(
                "AST死代码注入完成",
                f"成功注入 {self.injected_count} 个文件"
            )

            return True

        except Exception as e:
            self.logger.log_error(f"AST死代码注入失败: {e}")
            return False

    def _find_target_files(self, project_path: str) -> List[str]:
        """查找目标文件"""
        target_files = []

        for root, dirs, files in os.walk(project_path):
            # 跳过不需要的目录
            dirs[:] = [d for d in dirs if not d.startswith('.')
                      and d not in ['build', 'dist', '__pycache__',
                                   'node_modules', 'DummyCode']]

            for file in files:
                file_path = os.path.join(root, file)
                language = detect_language_for_file(file_path)

                # 只处理支持的语言
                if language in ['swift', 'java', 'kotlin', 'python', 'objc']:
                    target_files.append(file_path)

        return target_files

    def _analyze_code_structure(self, target_files: List[str]) -> None:
        """分析代码结构，找出函数和复杂度"""
        self.dead_code_locations.clear()

        for file_path in target_files:
            language = detect_language_for_file(file_path)

            if language == 'python':
                locations = self._analyze_python_structure(file_path)
            elif language == 'java':
                locations = self._analyze_java_structure(file_path)
            elif language == 'swift':
                locations = self._analyze_swift_structure(file_path)
            elif language == 'kotlin':
                locations = self._analyze_kotlin_structure(file_path)
            elif language == 'objc':
                locations = self._analyze_objc_structure(file_path)
            else:
                continue

            self.dead_code_locations.extend(locations)

    def _analyze_python_structure(self, file_path: str) -> List[DeadCodeLocation]:
        """分析Python代码结构"""
        locations = []

        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()

            tree = ast.parse(content)

            for node in ast.walk(tree):
                if isinstance(node, ast.FunctionDef):
                    # 计算函数复杂度
                    complexity_score = self._calculate_python_complexity(node)

                    # 检查是否有条件和循环
                    has_conditional = any(isinstance(n, (ast.If, ast.IfExp))
                                        for n in ast.walk(node))
                    has_loop = any(isinstance(n, (ast.For, ast.While))
                                 for n in ast.walk(node))

                    location = DeadCodeLocation(
                        file_path=file_path,
                        language='python',
                        function_name=node.name,
                        function_start_line=node.lineno,
                        function_end_line=node.end_lineno if hasattr(node, 'end_lineno') else node.lineno + 10,
                        complexity_score=complexity_score,
                        has_conditional=has_conditional,
                        has_loop=has_loop
                    )
                    locations.append(location)

        except Exception as e:
            self.logger.log_warning(f"分析Python结构失败 {file_path}: {e}")

        return locations

    def _calculate_python_complexity(self, node: ast.FunctionDef) -> int:
        """计算Python函数的圈复杂度"""
        complexity = 1  # 基础复杂度

        for child in ast.walk(node):
            if isinstance(child, (ast.If, ast.While, ast.For)):
                complexity += 1
            elif isinstance(child, ast.ExceptHandler):
                complexity += 1
            elif isinstance(child, ast.With):
                complexity += 1

        return complexity

    def _analyze_java_structure(self, file_path: str) -> List[DeadCodeLocation]:
        """分析Java代码结构"""
        locations = []

        try:
            # 尝试使用javalang
            try:
                import javalang
            except ImportError:
                return self._analyze_java_with_regex(file_path)

            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
                lines = content.split('\n')

            tree = javalang.parse.parse(content)

            for path, node in tree:
                if isinstance(node, javalang.tree.MethodDeclaration):
                    if node.body and 'abstract' not in (node.modifiers or []):
                        # 计算方法的行范围
                        start_line = self._find_line_number(lines, node.name, 'method')
                        end_line = start_line + 20  # 估计值

                        # 计算复杂度
                        complexity_score = self._calculate_java_complexity(node)

                        location = DeadCodeLocation(
                            file_path=file_path,
                            language='java',
                            function_name=node.name,
                            function_start_line=start_line,
                            function_end_line=end_line,
                            complexity_score=complexity_score,
                            has_conditional=self._has_java_conditional(node),
                            has_loop=self._has_java_loop(node)
                        )
                        locations.append(location)

        except Exception as e:
            self.logger.log_warning(f"分析Java结构失败 {file_path}: {e}")
            return self._analyze_java_with_regex(file_path)

        return locations

    def _analyze_java_with_regex(self, file_path: str) -> List[DeadCodeLocation]:
        """使用正则表达式分析Java（回退方案）"""
        import re
        locations = []

        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                lines = f.readlines()

            # 查找方法定义
            method_pattern = re.compile(
                r'^\s*(public|private|protected)?\s*(static)?\s*\w+\s+(\w+)\s*\([^)]*\)\s*\{'
            )

            for i, line in enumerate(lines):
                match = method_pattern.match(line)
                if match:
                    method_name = match.group(3)
                    if method_name not in ['main', 'toString', 'equals', 'hashCode']:
                        # 找到方法结束
                        end_line = self._find_method_end(lines, i)

                        location = DeadCodeLocation(
                            file_path=file_path,
                            language='java',
                            function_name=method_name,
                            function_start_line=i + 1,
                            function_end_line=end_line,
                            complexity_score=3,  # 默认中等复杂度
                            has_conditional=self._check_has_conditional(lines[i:end_line]),
                            has_loop=self._check_has_loop(lines[i:end_line])
                        )
                        locations.append(location)

        except Exception as e:
            self.logger.log_warning(f"正则分析Java失败 {file_path}: {e}")

        return locations

    def _calculate_java_complexity(self, node) -> int:
        """计算Java方法的复杂度"""
        complexity = 1

        # 遍历方法体统计控制流语句
        for statement in node.body:
            if hasattr(statement, '__class__'):
                class_name = statement.__class__.__name__
                if class_name in ['IfStatement', 'WhileStatement', 'ForStatement',
                                 'DoStatement', 'SwitchStatement']:
                    complexity += 1
                elif class_name == 'TryStatement':
                    complexity += len(getattr(statement, 'catches', []))

        return complexity

    def _has_java_conditional(self, node) -> bool:
        """检查Java方法是否有条件语句"""
        if not node.body:
            return False

        for statement in node.body:
            if hasattr(statement, '__class__'):
                if statement.__class__.__name__ in ['IfStatement', 'SwitchStatement']:
                    return True
        return False

    def _has_java_loop(self, node) -> bool:
        """检查Java方法是否有循环"""
        if not node.body:
            return False

        for statement in node.body:
            if hasattr(statement, '__class__'):
                if statement.__class__.__name__ in ['ForStatement', 'WhileStatement', 'DoStatement']:
                    return True
        return False

    def _find_line_number(self, lines: List[str], name: str, context: str) -> int:
        """查找符号所在的行号"""
        for i, line in enumerate(lines):
            if name in line:
                return i + 1
        return 1

    def _find_method_end(self, lines: List[str], start: int) -> int:
        """找到方法的结束行"""
        depth = 0
        for i in range(start, len(lines)):
            line = lines[i]
            depth += line.count('{') - line.count('}')
            if depth == 0 and '}' in line:
                return i + 1
        return len(lines)

    def _check_has_conditional(self, lines: List[str]) -> bool:
        """检查代码行中是否有条件语句"""
        conditional_keywords = ['if', 'else', 'switch', 'case']
        text = ' '.join(lines)
        return any(f' {keyword} ' in text or f' {keyword}(' in text
                  for keyword in conditional_keywords)

    def _check_has_loop(self, lines: List[str]) -> bool:
        """检查代码行中是否有循环"""
        loop_keywords = ['for', 'while', 'do']
        text = ' '.join(lines)
        return any(f' {keyword} ' in text or f' {keyword}(' in text
                  for keyword in loop_keywords)

    def _analyze_swift_structure(self, file_path: str) -> List[DeadCodeLocation]:
        """分析Swift代码结构"""
        import re
        locations = []

        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                lines = f.readlines()

            # 查找函数定义
            func_pattern = re.compile(r'^\s*func\s+(\w+)\s*\([^)]*\).*\{')

            for i, line in enumerate(lines):
                match = func_pattern.match(line)
                if match:
                    func_name = match.group(1)
                    end_line = self._find_method_end(lines, i)

                    location = DeadCodeLocation(
                        file_path=file_path,
                        language='swift',
                        function_name=func_name,
                        function_start_line=i + 1,
                        function_end_line=end_line,
                        complexity_score=3,
                        has_conditional=self._check_has_conditional(lines[i:end_line]),
                        has_loop=self._check_has_loop(lines[i:end_line])
                    )
                    locations.append(location)

        except Exception as e:
            self.logger.log_warning(f"分析Swift结构失败 {file_path}: {e}")

        return locations

    def _analyze_kotlin_structure(self, file_path: str) -> List[DeadCodeLocation]:
        """分析Kotlin代码结构"""
        import re
        locations = []

        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                lines = f.readlines()

            # 查找函数定义
            func_pattern = re.compile(r'^\s*fun\s+(\w+)\s*\([^)]*\).*\{')

            for i, line in enumerate(lines):
                match = func_pattern.match(line)
                if match:
                    func_name = match.group(1)
                    end_line = self._find_method_end(lines, i)

                    location = DeadCodeLocation(
                        file_path=file_path,
                        language='kotlin',
                        function_name=func_name,
                        function_start_line=i + 1,
                        function_end_line=end_line,
                        complexity_score=3,
                        has_conditional=self._check_has_conditional(lines[i:end_line]),
                        has_loop=self._check_has_loop(lines[i:end_line])
                    )
                    locations.append(location)

        except Exception as e:
            self.logger.log_warning(f"分析Kotlin结构失败 {file_path}: {e}")

        return locations

    def _analyze_objc_structure(self, file_path: str) -> List[DeadCodeLocation]:
        """分析ObjC代码结构"""
        import re
        locations = []

        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
                lines = content.split('\n')

            # 查找方法实现
            method_pattern = re.compile(r'^[-+]\s*\([^)]+\)\s*(\w+)')

            for i, line in enumerate(lines):
                match = method_pattern.match(line)
                if match:
                    method_name = match.group(1)
                    # 找到方法体
                    for j in range(i, min(i + 10, len(lines))):
                        if '{' in lines[j]:
                            end_line = self._find_method_end(lines, j)

                            location = DeadCodeLocation(
                                file_path=file_path,
                                language='objc',
                                function_name=method_name,
                                function_start_line=j + 1,
                                function_end_line=end_line,
                                complexity_score=3,
                                has_conditional=self._check_has_conditional(lines[j:end_line]),
                                has_loop=self._check_has_loop(lines[j:end_line])
                            )
                            locations.append(location)
                            break

        except Exception as e:
            self.logger.log_warning(f"分析ObjC结构失败 {file_path}: {e}")

        return locations

    def _inject_with_ast(self, file_path: str, complexity: str) -> bool:
        """使用AST信息注入死代码"""
        try:
            # 找到此文件的注入位置
            file_locations = [loc for loc in self.dead_code_locations
                            if loc.file_path == file_path]

            if not file_locations:
                return False

            # 读取文件内容
            with open(file_path, 'r', encoding='utf-8') as f:
                lines = f.readlines()

            # 获取配置
            config = self.COMPLEXITY_CONFIG.get(complexity, self.COMPLEXITY_CONFIG['medium'])

            # 选择合适的函数注入
            # 优先选择复杂度较低的函数，避免使已复杂的函数更复杂
            location = min(file_locations, key=lambda x: x.complexity_score)

            # 生成死代码
            dead_code = self._generate_advanced_dead_code(
                location.language,
                config,
                location
            )

            # 在函数开始处注入
            if 0 < location.function_start_line <= len(lines):
                # 找到函数体的第一行（跳过函数签名）
                insert_line = location.function_start_line
                for i in range(location.function_start_line - 1,
                             min(location.function_start_line + 5, len(lines))):
                    if '{' in lines[i]:
                        insert_line = i + 2  # 在 { 后面插入
                        break

                # 获取正确的缩进
                indent = self._get_indentation(lines[insert_line - 1] if insert_line > 0 else "")

                # 格式化死代码
                formatted_dead_code = self._format_dead_code(dead_code, indent)

                # 插入死代码
                lines.insert(insert_line - 1, formatted_dead_code)

                # 写回文件
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.writelines(lines)

                self.logger.log_file_processing(
                    file_path,
                    f"AST死代码注入成功 (函数: {location.function_name}, 复杂度: {complexity})"
                )
                return True

        except Exception as e:
            self.logger.log_warning(f"AST死代码注入失败 {file_path}: {e}")
            return False

    def _inject_with_regex(self, file_path: str, complexity: str) -> bool:
        """使用正则表达式注入死代码（回退方案）"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()

            language = detect_language_for_file(file_path)

            # 查找函数
            import re
            functions = self._find_functions_regex(content, language)

            if not functions:
                return False

            # 获取配置
            config = self.COMPLEXITY_CONFIG.get(complexity, self.COMPLEXITY_CONFIG['medium'])

            # 对每个函数注入死代码
            offset = 0
            for func_name, func_start, func_end in functions:
                # 生成死代码
                dead_code = self._generate_simple_dead_code(
                    language,
                    config['branches_per_function'],
                    config['use_opaque_predicates']
                )

                # 插入死代码
                injection_pos = func_start + offset
                content = (
                    content[:injection_pos] +
                    dead_code +
                    content[injection_pos:]
                )

                offset += len(dead_code)

            # 写回文件
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)

            self.logger.log_file_processing(
                file_path,
                f"正则死代码注入成功 (函数数: {len(functions)})"
            )
            return True

        except Exception as e:
            self.logger.log_warning(f"正则死代码注入失败 {file_path}: {e}")
            return False

    def _find_functions_regex(self, content: str, language: str) -> List[Tuple[str, int, int]]:
        """使用正则查找函数"""
        import re
        functions = []

        if language == 'swift':
            pattern = r'func\s+(\w+)\s*\([^)]*\)\s*(?:->\s*\w+\s*)?\{'
        elif language == 'java':
            pattern = r'(?:public|private|protected|static)?\s+\w+\s+(\w+)\s*\([^)]*\)\s*\{'
        elif language == 'kotlin':
            pattern = r'fun\s+(\w+)\s*\([^)]*\)\s*(?::\s*\w+\s*)?\{'
        else:
            return functions

        matches = re.finditer(pattern, content)

        for match in matches:
            func_name = match.group(1)
            func_start = match.end()
            func_end = self._find_closing_brace(content, func_start)
            functions.append((func_name, func_start, func_end))

        return functions

    def _find_closing_brace(self, content: str, start: int) -> int:
        """查找匹配的右大括号"""
        depth = 1
        i = start

        while i < len(content) and depth > 0:
            if content[i] == '{':
                depth += 1
            elif content[i] == '}':
                depth -= 1
            i += 1

        return i

    def _generate_advanced_dead_code(self, language: str, config: dict,
                                    location: DeadCodeLocation) -> str:
        """生成高级死代码"""
        dead_code_parts = []

        # 1. 添加死变量声明
        dead_vars = self._generate_dead_variables(language, config['dead_variable_count'])
        dead_code_parts.append(dead_vars)

        # 2. 添加不透明谓词分支
        if config['use_opaque_predicates']:
            for _ in range(config['branches_per_function']):
                predicate_block = self._generate_opaque_predicate_block(
                    language, location.complexity_score
                )
                dead_code_parts.append(predicate_block)

        # 3. 添加控制流混淆
        if config['use_control_flow_obfuscation']:
            control_flow = self._generate_control_flow_obfuscation(language)
            dead_code_parts.append(control_flow)

        # 4. 如果函数没有条件语句，添加一个
        if not location.has_conditional:
            fake_conditional = self._generate_fake_conditional(language)
            dead_code_parts.append(fake_conditional)

        return '\n'.join(dead_code_parts)

    def _generate_simple_dead_code(self, language: str, branch_count: int,
                                  use_opaque: bool) -> str:
        """生成简单死代码"""
        dead_code_blocks = []

        for _ in range(branch_count):
            if use_opaque:
                block = self._generate_opaque_predicate_block(language, 1)
            else:
                block = self._generate_always_false_block(language)
            dead_code_blocks.append(block)

        return '\n'.join(dead_code_blocks)

    def _generate_dead_variables(self, language: str, count: int) -> str:
        """生成死变量声明"""
        import string
        import random

        vars_code = []

        for i in range(count):
            var_name = f"_unused_{i}_{random.randint(1000, 9999)}"
            value = random.choice([
                random.randint(1, 1000),
                f'"{self._random_string(10)}"',
                'true' if language != 'python' else 'True',
                'false' if language != 'python' else 'False',
                'null' if language != 'python' else 'None'
            ])

            if language == 'python':
                vars_code.append(f"    {var_name} = {value}")
            elif language in ['java', 'kotlin']:
                if isinstance(value, int):
                    vars_code.append(f"    int {var_name} = {value};")
                elif value.startswith('"'):
                    vars_code.append(f"    String {var_name} = {value};")
                else:
                    vars_code.append(f"    boolean {var_name} = {value};")
            elif language == 'swift':
                vars_code.append(f"    let {var_name} = {value}")
            elif language == 'objc':
                if isinstance(value, int):
                    vars_code.append(f"    int {var_name} = {value};")
                elif value.startswith('"'):
                    vars_code.append(f"    NSString *{var_name} = @{value};")
                else:
                    vars_code.append(f"    BOOL {var_name} = {value.upper()};")

        return '\n'.join(vars_code)

    def _generate_opaque_predicate_block(self, language: str, complexity: int) -> str:
        """生成不透明谓词块"""
        # 复杂的不透明谓词
        complex_predicates = [
            "(x * x + y * y) >= 0",  # 平方和总是非负
            "(x & -x) == (x & -x)",  # 位运算恒真
            "((x ^ y) ^ y) == x",  # XOR的自反性
            "(x | 0) == x",  # OR with 0
            "((x * 2) / 2) == x || ((x * 2 + 1) / 2) == x"  # 整数除法
        ]

        simple_predicates = [
            "x * x >= 0",  # 平方非负
            "(x + 1) > x || x == x",  # 递增或自等
            "true || x > 0"  # 短路求值
        ]

        predicates = complex_predicates if complexity > 3 else simple_predicates
        predicate = random.choice(predicates)

        if language == 'python':
            return f"""
    # Opaque predicate - always evaluates predictably
    x = random.randint(1, 100)
    y = random.randint(1, 100)
    if {predicate}:
        pass  # This branch is taken
    else:
        # Dead code - never executed
        _dead = "{self._random_string(20)}"
        print(_dead)"""

        elif language == 'java':
            return f"""
    // Opaque predicate - mathematically certain
    int x = new java.util.Random().nextInt(100) + 1;
    int y = new java.util.Random().nextInt(100) + 1;
    if ({predicate}) {{
        // This branch is always taken
    }} else {{
        // Dead code - never reached
        String _dead = "{self._random_string(20)}";
        System.out.println(_dead);
    }}"""

        elif language == 'swift':
            return f"""
    // Opaque predicate
    let x = Int.random(in: 1...100)
    let y = Int.random(in: 1...100)
    if {predicate} {{
        // Always executed
    }} else {{
        // Never reached
        let _dead = "{self._random_string(20)}"
        print(_dead)
    }}"""

        elif language == 'kotlin':
            return f"""
    // Opaque predicate
    val x = (1..100).random()
    val y = (1..100).random()
    if ({predicate}) {{
        // Always true
    }} else {{
        // Dead branch
        val _dead = "{self._random_string(20)}"
        println(_dead)
    }}"""

        elif language == 'objc':
            return f"""
    // Opaque predicate
    int x = arc4random_uniform(100) + 1;
    int y = arc4random_uniform(100) + 1;
    if ({predicate}) {{
        // Always taken
    }} else {{
        // Never executed
        NSString *_dead = @"{self._random_string(20)}";
        NSLog(@"%@", _dead);
    }}"""

        return ""

    def _generate_always_false_block(self, language: str) -> str:
        """生成恒假条件块"""
        if language == 'python':
            return """
    if False:
        _unreachable = "This code is never executed"
        print(_unreachable)"""

        elif language == 'java':
            return """
    if (false) {
        String unreachable = "Never executed";
        System.out.println(unreachable);
    }"""

        elif language == 'swift':
            return """
    if false {
        let unreachable = "Never executed"
        print(unreachable)
    }"""

        elif language == 'kotlin':
            return """
    if (false) {
        val unreachable = "Never executed"
        println(unreachable)
    }"""

        elif language == 'objc':
            return """
    if (NO) {
        NSString *unreachable = @"Never executed";
        NSLog(@"%@", unreachable);
    }"""

        return ""

    def _generate_control_flow_obfuscation(self, language: str) -> str:
        """生成控制流混淆代码"""
        if language == 'python':
            return """
    # Control flow obfuscation
    _state = 0
    while _state < 3:
        if _state == 0:
            _state = 1
        elif _state == 1:
            _state = 2
        else:
            break"""

        elif language in ['java', 'kotlin']:
            return """
    // Control flow obfuscation
    int _state = 0;
    while (_state < 3) {
        switch (_state) {
            case 0: _state = 1; break;
            case 1: _state = 2; break;
            default: _state = 3; break;
        }
    }"""

        elif language == 'swift':
            return """
    // Control flow obfuscation
    var _state = 0
    while _state < 3 {
        switch _state {
        case 0: _state = 1
        case 1: _state = 2
        default: _state = 3
        }
    }"""

        elif language == 'objc':
            return """
    // Control flow obfuscation
    int _state = 0;
    while (_state < 3) {
        if (_state == 0) _state = 1;
        else if (_state == 1) _state = 2;
        else break;
    }"""

        return ""

    def _generate_fake_conditional(self, language: str) -> str:
        """生成假的条件语句"""
        condition = "x % 2 == 0"

        if language == 'python':
            return f"""
    # Fake conditional
    x = random.randint(1, 100)
    if {condition}:
        pass  # Even number
    else:
        pass  # Odd number"""

        elif language in ['java', 'kotlin']:
            return f"""
    // Fake conditional
    int x = new java.util.Random().nextInt(100);
    if ({condition}) {{
        // Even path
    }} else {{
        // Odd path
    }}"""

        elif language == 'swift':
            return f"""
    // Fake conditional
    let x = Int.random(in: 1...100)
    if {condition} {{
        // Even path
    }} else {{
        // Odd path
    }}"""

        elif language == 'objc':
            return f"""
    // Fake conditional
    int x = arc4random_uniform(100);
    if ({condition}) {{
        // Even path
    }} else {{
        // Odd path
    }}"""

        return ""

    def _get_indentation(self, line: str) -> str:
        """获取行的缩进"""
        indent = ""
        for char in line:
            if char in [' ', '\t']:
                indent += char
            else:
                break
        return indent if indent else "    "

    def _format_dead_code(self, code: str, indent: str) -> str:
        """格式化死代码，添加适当的缩进"""
        lines = code.split('\n')
        formatted_lines = []

        for line in lines:
            if line.strip():
                # 保持相对缩进
                if line.startswith('    '):
                    formatted_lines.append(indent + line)
                else:
                    formatted_lines.append(line)

        return '\n'.join(formatted_lines) + '\n'

    def _random_string(self, length: int) -> str:
        """生成随机字符串"""
        import string
        return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

    def get_statistics(self) -> dict:
        """获取注入统计"""
        return {
            'injected_count': self.injected_count,
            'analyzed_functions': len(self.dead_code_locations),
            'average_complexity': sum(loc.complexity_score for loc in self.dead_code_locations) / max(len(self.dead_code_locations), 1)
        }